import axios from "axios";
import { Message, Loading } from "element-ui";
let loading;

function startLoading() {
    loading = Loading.service({
        lock: true,
        text: "拼命加载中...",
        background: "rgba(0,0,0,7)",
    });
}

function endLoading() {
    loading.close();
}
//请求拦截
axios.interceptors.request.use(
    (config) => {
        startLoading();
        if (localStorage.FundToken) {
            //配置统一请求头
            config.headers.Authorization = localStorage.FundToken;
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);
//响应拦截
axios.interceptors.response.use(
    response => {
        endLoading();
        return response;
    },
    error => {
        // 错误提醒
        endLoading()
        Message.error(error.response.data)

        const { status } = error.response
            //===判断401就刷新token===
        if (
            status &&
            status === 401 &&
            status.statusText === 'UNAUTHORIZED'
        ) {
            if (getItem() && getItem().refresh_token) {
                axios({
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                        // Authorization: 'Bearer ' + getItem().refresh_token,
                        // 如果不加bearer 空格 的话，就会报错 wrong token
                        Authorization: `Bearer ${getItem().refresh_token}`,
                    },
                }).then((res) => {
                    setItem({
                        token: res.data.data.token, // toekn值使用最新的
                        refresh_token: getItem().refresh_token, // 刷新toekn还是使用以前的，
                    });
                    request(error);
                });
            }
        }
        return Promise.reject(error)
    }
);

export default axios;